package com.example.blogdemo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.blankj.utilcode.util.LogUtils
import com.example.blogdemo.databinding.ActivityShowFragmentBinding

class ShowFragmentActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityShowFragmentBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val fragment = intent.getStringExtra("fragment") ?: BlankFragment::class.java.name
        LogUtils.e(fragment)
        val title = intent.getStringExtra("title") ?: "莫得名字"
        showFragment(fragment, supportFragmentManager, R.id.frame)
        binding.tvTitle.text = title
    }
}

fun getSowFragment(fragment:Class<*>, title: String = "莫得名字"): Bundle {
    return bundleOf("fragment" to fragment.name, "title" to title)
}

fun showFragment(className: String?, fragmentManager: FragmentManager, id: Int): Fragment? {
    var fragment: Fragment? = null
    try {
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        //隐藏所有的那个啥。
        for (fra in fragmentManager.getFragments()) {
            fragmentTransaction.hide(fra)
        }
        val fragmentByTag: Fragment? = fragmentManager.findFragmentByTag(className)
        if (fragmentByTag != null) {
            fragmentTransaction.show(fragmentByTag)
        } else {
            fragment = Class.forName(className).newInstance() as Fragment
            fragmentTransaction.add(id, fragment, className)
        }
        //添加到返回栈中
        //  fragmentTransaction.addToBackStack(className);
        fragmentTransaction.commitAllowingStateLoss()
    } catch (e: InstantiationException) {
        e.printStackTrace()
    } catch (e: IllegalAccessException) {
        e.printStackTrace()
    } catch (e: ClassNotFoundException) {
        e.printStackTrace()
    }
    return fragment
}
